from mss import mss
from PIL import Image


class Detect():
	def __init__(self):
		self.grabber = mss()
		self.monitor = self.grabber.monitors[1]

	def capture(self):
		image_captured = self.grabber.grab(self.monitor)
		image = Image.frombytes('RGB', image_captured.size, image_captured.bgra, 'raw', 'BGRX')
		return image

	def find_matches(self, match):
		image = self.capture()
		matches = []
		image_map = image.load()

		x_max = image.size[0]
		y_max = image.size[1]
		for x in range(0, x_max):
			for y in range(0, y_max):
				pixel = image_map[x, y]
				if pixel == match:
					matches.append((x, y))

		return matches

	def get_location_value(self, x, y):
		image = self.capture()
		image_map = image.load()
		return image_map[x, y]

	def recover(self):
		image = self.capture()
		matches = {}
		image_map = image.load()

		x_max = image.size[0]
		y_max = image.size[1]
		for x in range(0, x_max):
			for y in range(0, y_max):
				pixel = image_map[x, y]
				if matches.get(pixel) is None:
					matches[pixel] = 1
				else:
					matches[pixel] += 1

		for pixel in matches:
			if matches[pixel] == 1:
				return pixel

if __name__ == '__main__':
	detect = Detect()
	#print(detect.recover())
	#match = (255, 0, 0)
	#matches = detect.find_matches(match)
	#print(len(matches))
	# print(matches)

	value = detect.get_location_value(246, 1145)
	print(value)
	# print(len(matches))
	# print(matches)



	#print(image_map[0, 0])
